package cn.vortex.device.web.servlet;

import cn.vortex.device.service.*;
import cn.vortex.device.service.impl.*;
import cn.vortex.device.tool.JdbcUtil;
import cn.vortex.device.tool.ResMessageBuilder;
import cn.vortex.device.vo.*;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet(name = "UserServlet", urlPatterns = "/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();


    public ResMessage page(HttpServletRequest request, HttpServletResponse response) {

        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        String account = request.getParameter("account");
        String username = request.getParameter("username");
        String roleID = request.getParameter("roleId");

        Map<String, Object> params = new HashMap<>();
        if (account != null && !"".equals(account)) {
            params.put("account", account);
        }
        if (username != null && !"".equals(username)) {
            params.put("doPerson", username);
        }
        if (checkField(roleID)){
            params.put("roleID",roleID);
        }
        PageVo<User> pageVo = null;
        try {
            Object user = request.getSession().getAttribute("USER");
            if (user != null){//判断user 是否存在
                if (user instanceof User){//判断user是否是User的实例化对象，是返回true
                    User _user = (User) user;//将user转换为User对象
                    if (_user.getRoleId() == 1) {//判断用户的身份ID是否符合要求
                        //普通用户只能查看自己的申请信息
                        pageVo = userService.pageObj(_user.getUsername(), page, limit, params);
                    } else if (_user.getRoleId() == 2){
                        //管理员可以查看所有人的申请信息
                        pageVo = userService.pageObj(page, limit, params);
                    }
                } else {
                    throw new RuntimeException("传入的USER不符合要求！");//如果user对象不是User类的实例化对象抛出异常
                }
            } else {
                response.sendRedirect(request.getContextPath()+"/error/403.html");//不满足将请求转发至403错误页面
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResMessage(200, "fail", "服务器错误");
        }

        return new ResMessage(200, "success", pageVo);
    }

    public ResMessage add(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String account = request.getParameter("account");
        String password = request.getParameter("password");
        String username = request.getParameter("username");
        String roleID = request.getParameter("roleId");


        ResMessage resMessage;
        if (userService.getObjByAccount(account) == null) {
            User user = new User();
            if (checkField(account)) {
                user.setAccount(account);
            }
            if (checkField(password)) {
                user.setPassword(password);
            }
            if (checkField(username)) {
                user.setUsername(username);
            }
            if (checkField(roleID)){
                //switch开关时使用
                //if (roleID.equals("on")){
                //    user.setRoleId(2);
                //} else {
                //    user.setRoleId(1);
                //}
                //使用check-box时使用
                user.setRoleId(Integer.parseInt(roleID));
            }

            resMessage = null;
            try {

                JdbcUtil.startTransaction();

                if (userService.addObj(user)) {
                    resMessage = ResMessageBuilder.success("success", "添加用户成功");
                } else {
                    resMessage = ResMessageBuilder.resMessage(200, "fail", "添加用户失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
                JdbcUtil.rollback();
                return ResMessageBuilder.resMessage(200, "fail", "系统错误");
            } finally {
                JdbcUtil.commit();
            }
        } else {
            resMessage = ResMessageBuilder.resMessage(200, "fail", "该账号已存在");
        }

        return resMessage;
    }


    public ResMessage delete(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        if (id == null || "".equals(id)) {
            return new ResMessage(200, "fail", "参数错误！");
        }

        try {
            if (userService.deleteObjById(Integer.parseInt(id))) {
                return new ResMessage(200, "success", "删除成功！");
            } else return new ResMessage(200, "fail", "删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResMessage(500, "fail", "系统错误");
        }

    }

    public ResMessage edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        String account = request.getParameter("account");
        String passwordNew = request.getParameter("password-new");
        String username = request.getParameter("username");
        String roleID = request.getParameter("roleId");

        ResMessage resMessage = null;
        try {

            JdbcUtil.startTransaction();
            if (checkField(id)) {
                User user = userService.getObjById(Integer.parseInt(id));

                if (user != null) {
                    if (checkField(account)) {
                        user.setAccount(account);
                    }
                    if (checkField(passwordNew)) {
                        user.setPassword(passwordNew);
                    }
                    if (checkField(username)) {
                        user.setUsername(username);
                    }
                    if (checkField(roleID)){
                        //switch开关时使用
                        //if (roleID.equals("on")){
                        //    user.setRoleId(2);
                        //} else {
                        //    user.setRoleId(1);
                        //}
                        //使用check-box时使用
                        user.setRoleId(Integer.parseInt(roleID));
                        System.out.println(user.getRoleId());
                    }
                    userService.updateObj(user);
                    resMessage = ResMessageBuilder.success("success", "修改信息成功");
                } else {
                    resMessage = ResMessageBuilder.resMessage(200, "fail", "修改信息失败");
                }
            } else {
                resMessage = ResMessageBuilder.resMessage(200, "fail", "参数非法");
            }

        } catch (Exception e) {
            e.printStackTrace();
            JdbcUtil.rollback();
            return ResMessageBuilder.resMessage(200, "fail", "系统错误");
        } finally {
            JdbcUtil.commit();
        }

        return resMessage;
    }


    public ResMessage batchDel(HttpServletRequest request, HttpServletResponse response) {

        String ids = request.getParameter("ids");
        ResMessage resMessage = null;
        Set<Integer> idsSet = new HashSet<>();
        if (ids != null && !"".equals(ids)) {
            String[] split = ids.split(",");
            for (String s : split) {
                idsSet.add(Integer.parseInt(s));
            }
            try {
                if (userService.deleteObjList(idsSet)) {
                    resMessage = new ResMessage(200, "success", "删除成功");
                } else {
                    resMessage = resMessage = new ResMessage(200, "fail", "删除失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new ResMessage(200, "fail", "服务器错误");
            }

        } else {
            resMessage = new ResMessage(200, "fail", "参数错误");
        }

        return resMessage;
    }


    boolean checkField(String field) {
        return field != null && !"".equals(field);
    }



}
